import 'dart:io';
import 'dart:ui';

import 'package:eyepetizer_example/page/watch_history_page.dart';
import 'package:eyepetizer_example/utils/cache_manager.dart';
import 'package:eyepetizer_example/widget/go_navigation.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';

class MinePage extends StatefulWidget {
  const MinePage({Key? key}) : super(key: key);
  @override
  State<StatefulWidget> createState() => _MinePageState();
}

class _MinePageState extends State<StatefulWidget> with AutomaticKeepAliveClientMixin{
  final picker = ImagePicker();

  @override
  void initState() {
    super.initState();
    CacheManager.preInit();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    // 可以移除元素的pandding，注意:要指定移除哪个方向的padding
    return MediaQuery.removePadding(context: context,
        // 移除上面的padding
        child: ListView(
          children: [
            // 头像
            _head(),
            // 中间的收藏、评论
            _like(),
            // 分割线
            _divider(),
            // 几个设置的widget
            //... 散布运算符，将列表的所有元素插入另一个列表
            ..._listSetting()
          ],
        ));
  }

  @override
  bool get wantKeepAlive => true;

  Widget _head() {
    return Stack(
      alignment: Alignment.center,
      children: [
        // 高斯模糊背景
        //... 散布运算符，将列表的所有元素插入另一个列表
        ..._headBackground(),
        // 内容
        _headContent(),
      ],
    );
  }

  /// 中间的收藏、评论
  Widget _like() {
    return Padding(
      padding: const EdgeInsets.only(top: 20),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: <Widget>[
          _imageAndText('images/icon_like_grey.png', '收藏'),
          Container(
            width: 0.5,
            height: 40,
            decoration: const BoxDecoration(color: Colors.grey),
          ),
          _imageAndText('images/icon_comment_grey.png', '评论'),
        ],
      ),
    );
  }

// 图片与文本组合
  Widget _imageAndText(String image, String text) {
    return Row(
      children: <Widget>[
        Image.asset(image, width: 20, height: 20),
        Padding(
          padding: const EdgeInsets.only(left: 10),
          child: Text(
            text,
            style: const TextStyle(fontSize: 14, color: Colors.grey),
          ),
        ),
      ],
    );
  }

  Widget _divider() {
    return Padding(
      padding: const EdgeInsets.only(top: 20),
      child: Container(
        height: 0.5,
        decoration: const BoxDecoration(color: Colors.grey),
      ),
    );
  }

  _listSetting() {
    return [
      _setting('我的消息'),
      _setting('我的缓存'),
      _setting(
        '观看记录',
        callback: () {
          GoNavigator.toPage(context, const WatchHistoryPage());
        },
      ),
      _setting('意见反馈')
    ];
  }

// 设置
  Widget _setting(String text, {VoidCallback? callback}) {
    return InkWell(
      onTap: callback,
      child: Container(
        alignment: Alignment.center,
        padding: const EdgeInsets.only(top: 30),
        child: Text(
          text,
          style: const TextStyle(fontSize: 16, color: Colors.black87),
        ),
      ),
    );
  }

  List<Widget> _headBackground() {
    return [
      Positioned.fill(
        child: Image(
          image: _avatarImage(),
          fit: BoxFit.fill,
        ),
      ),
      Positioned.fill(
        // 高斯模糊
        child: BackdropFilter(
          filter: ImageFilter.blur(sigmaX: 10, sigmaY: 10),
          child: Container(color: Colors.white.withOpacity(0.0),),
        ),
      )
    ];
  }

  Widget _headContent() {
    return Column(
      children: [
        GestureDetector(
          child: Padding(
            padding: const EdgeInsets.only(top: 45),
            child: CircleAvatar(
              backgroundColor: Colors.transparent,
              radius: 44,
              backgroundImage: _avatarImage(),
            ),
          ),
          onTap: () {
            // 选择图片
            _showSelectPhotoDialog(context);
          },
        ),
        const Padding(
          padding: EdgeInsets.only(top: 20),
          child: Text(
            '小白马',
            style: TextStyle(
                fontSize: 20, fontWeight: FontWeight.bold, color: Colors.white),
          ),
        ),
        const Padding(
            padding: EdgeInsets.only(top: 10),
            child: Text(
              '查看个人主页 >',
              style: TextStyle(fontSize: 12, color: Colors.white),
            )),
      ],
    );
  }

  File? _imageFile;
  ImageProvider _avatarImage() {
    if (_imageFile != null) {
      return FileImage(_imageFile!);
    } else {
      return const AssetImage("images/ic_img_avatar.png");
    }
  }

  // 点击头像后弹出dialog
  void _showSelectPhotoDialog(BuildContext context) {
    // 类似Android 的 BottomSheetDialog，最多半个屏幕高
    showModalBottomSheet(context: context,
        builder: (context) {
            return Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                _bottomWidget('拍照', () {
                  GoNavigator.back(context);
                  _getImage(ImageSource.camera);
                }),
                _bottomWidget('相册', () {
                  GoNavigator.back(context);
                  _getImage(ImageSource.gallery);
                }),
                _bottomWidget('取消', () {
                  GoNavigator.back(context);
                }),
              ],
            );
        }
    );
  }

  Widget _bottomWidget(String text, VoidCallback callback) {
    return ListTile(
      title: Text(text, textAlign: TextAlign.center,),
      onTap: callback,
    );
  }

//模拟头像选择修改，目前存储在本地，实际开发应当上传到云存储平台
  void _getImage(ImageSource gallery) async{
    // 从相册获取或者拍照
    var imageFile = await picker.pickImage(source: gallery);
    setState(() {
      if(imageFile != null) {
        _imageFile = File(imageFile.path);
      }
    });
    // 将图片的路径缓存起来
    CacheManager.preInit().then((cacheManager) {
      if(_imageFile != null) {
        cacheManager.set("user_avatar_path", _imageFile!.path);
      }
    });
  }

}